package com.suxin.socket.vaca.config;

import com.sun.istack.internal.NotNull;
import com.suxin.socket.vaca.model.User;
import com.suxin.socket.vaca.model.WsResponse;
import com.suxin.socket.vaca.other.utils.JwtAuthenticationConfig;
import com.suxin.socket.vaca.other.utils.JwtUtil;
import com.suxin.socket.vaca.other.utils.SxToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname WebSocketServer
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/10/3 14:24
 * @Created by ASUS
 */
@Slf4j
@ServerEndpoint(value = "/ws/{access}")
@Component
public class WebSocketServer {

    private static JwtAuthenticationConfig config;

    @Autowired
    public void setJwtAuthenticationConfig(JwtAuthenticationConfig jwtAuthenticationConfig) {
        config = jwtAuthenticationConfig;
    }

    public static final Map<Integer, User> CLIENTS = new ConcurrentHashMap<>(8);

    private User user;

    @OnOpen
    public void onOpen(@NotNull @PathParam("access") String access, Session session) throws Exception {
        user = new User();
        user.setSession(session);
        Boolean isValid = JwtUtil.isValid(config, access);
        SxToken sxToken = JwtUtil.getSxToken(config, access);
        if (!isValid) {
            WsResponse response = WsResponse.builder()
                    .code(WsResponse.Stat.INVALID_TOKEN.getCode())
                    .data(WsResponse.Stat.INVALID_TOKEN.getDesc())
                    .build();
            user.send(response.toString());
            throw new RuntimeException("身份信息错误!");
        }
        // 初始化登录用户信息
        user.setId(sxToken.getUserId());
        user.setName(sxToken.getUsername());
        user.setRegistrationId(sxToken.getRegistrationId());
        user.refresh();
        CLIENTS.put(user.getId(), user);
    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }


}